#coding=utf-8

import re
import os

name_re = re.compile(r"\'([^\']*)\'")
name_line_re = re.compile(r"    _name")

def get_security_config(file_names,target_file):
    fwrite = open(target_file, 'w')
    head_str = "id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink"
    fwrite.write(head_str)
    fwrite.write("\n")
    fwrite.close()
    name_re = re.compile(r"\'([^\']*)\'")
    for file in file_names:
        if os.path.exists(file):
            if os.path.isfile(file):
                write_security_config(file,target_file)
            else:
                file_list = os.listdir(file)
                for file in file_list:
                    if endwith(file,'.py'):
                        write_security_config(file,target_file)


def endwith(s,*endstring):
    array = map(s.endswith,endstring)
    if True in array:
        return True
    else:
        return False

def write_security_config(file_name,target_file):
    fwrite = open(target_file, 'a')
    with open(file_name, 'r') as f:
        for line in f.readlines():
            if name_line_re.findall(line):
                names = name_re.findall(line.strip())
                if names:
                    print names
                    names_formate = names[0].replace('.', '_')
                    print names_formate
                    first = "access_{}_user,{}.user,model_{},base.group_user,1,0,0,0".format(names_formate,
                                                                                                    names[0],
                                                                                                    names_formate)
                    second = "access_{}_user_operate,{}.user,model_{},isleep_group.group_eroad_bracelet_operate,1,1,1,0".format(
                        names_formate, names[0], names_formate)
                    third = "access_{}_user_group_system,{}.user,model_{},base.group_system,1,1,1,1".format(
                        names_formate, names[0], names_formate)
                    print first
                    print second
                    print third
                    fwrite.write(first)
                    fwrite.write("\n")
                    fwrite.write(second)
                    fwrite.write("\n")
                    fwrite.write(third)
                    fwrite.write("\n")
                    fwrite.write("\n")
    fwrite.close()

if __name__ =='__main__':

    file_name = [
        '../isleep_patient_half_moon_report'
    ]
    new_file_name = 'security_tmp.txt'
    get_security_config(file_name,new_file_name)




